package com.yhy.dubbo.service.mongo;

import com.yhy.domain.mongo.FollowUser;
import com.yhy.domain.mongo.Video;
import com.yhy.domain.vo.PageResult;
import com.yhy.dubbo.api.mongo.VideoApi;
import com.yhy.dubbo.service.utils.IdService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Override
    public void save(Video video) {
        video.setId(new ObjectId());
        video.setCreated(System.currentTimeMillis());
        video.setVid(idService.getNextId("video"));
        mongoTemplate.save(video);
    }

    @Override
    public PageResult queryVideoList(Integer page, Integer pagesize) {

        long count = mongoTemplate.count(new Query(), Video.class);

        Query query = new Query()
                .skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        return new PageResult(page,pagesize, (int) count,videoList);
    }

    @Override
    public void saveFollowUser(FollowUser followUser) {
        followUser.setId(new ObjectId());
        followUser.setCreated(System.currentTimeMillis());
        mongoTemplate.save(followUser);
    }

    @Override
    public void deleteFollowUser(FollowUser followUser) {
        Criteria criteria = Criteria.where("userId").is(followUser.getUserId())
                .and("followUserId").is(followUser.getFollowUserId());
        mongoTemplate.remove(new Query(criteria),FollowUser.class);
    }

    @Override
    public PageResult findAll(Integer page, Integer pagesize, Long uid) {
        Criteria criteria = Criteria.where("userId").is(uid);

        long count = mongoTemplate.count(new Query(criteria), Video.class);

        Query query = new Query(criteria)
                .skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        List<Video> videoList = mongoTemplate.find(query, Video.class);
        return new PageResult(page,pagesize, (int) count,videoList);
    }

    //根据publishId查询video 用于小视频推荐 发送中间件消息
    @Override
    public Video findById(String publishId) {
        return mongoTemplate.findById(new ObjectId(publishId),Video.class);
    }

    @Override
    public Video findByVid(Long vid) {
        Criteria criteria = Criteria.where("vid").is(vid);
        return mongoTemplate.findOne(new Query(criteria),Video.class);
    }
}